console.log('进入到static.js')
let fs = require('fs')
// var css = fs.readFileSync('./static/index.css');
// var js = fs.readFileSync('./static/index.js');//直接返回文本
// var img = fs.readFileSync('./static/node.jpg');//直接显示图片
// var mp3 = fs.readFileSync('./static/chengdu.mp3');//返回音频直接是下载音频
function getStatic (req,res,url){
    let pathname = url.pathname
    var file = ''
            if(pathname.indexOf('/')>-1){
                var pathArr = pathname.split('/');
                if(pathArr[pathArr.length-1].indexOf('.')){//说明是静态文件
                    try{//尝试读取指定问文件
                        file =  fs.readFileSync('.' + pathname);
                    }catch(err){//文件不存在
                        console.log(err)
                        res.end("404 error! File not found.");
                    }
                    // if(fsExistsSync('.' + pathname)){
                    //     file =  fs.readFileSync('.' + pathname);
                    // }else{
                    //     res.end("404 error! File not found.");
                    // }
                }else{
                    res.writeHead(404, { "Content-Type": "text/plain" });
                res.end("404 error! File not found.");
                }
            }
        if(/.html$/.test(pathname)){
            res.writeHead(200, {
                "Content-Type": "text/html; charset=UTF-8"
            });
            res.end(file.toString()); 
        }else if(/\.js$/.test(pathname)){//js
            res.writeHead(200, {
                "Content-Type": "application/javascript;charset=UTF-8"
            });
            res.end(file.toString());  
        }else if(/\.css$/.test(pathname)){//css
            res.writeHead(200, {
                "Content-Type": "text/css;charset=UTF-8"
            });
            res.end(file.toString());  
        }else if(/(\.png)|(\.jpg)$/.test(pathname)){//img
            res.writeHead(200, {
                "Content-Type": "image/jpeg;charset=UTF-8"
            });
            res.end(file)
        }else if(/\.mp3/.test(pathname)){
            res.writeHead(200, {
                "Content-Type": "audio/mpeg;charset=UTF-8"
            });
             res.end(file); 
        }else{
            res.writeHead(404, { "Content-Type": "text/plain" });
            res.end("404 error! File not found.");
        }
           
} 
/**判断文件是否存在 */
function fsExistsSync(path) {
    try{
        fs.accessSync(path,fs.F_OK);
    }catch(e){
        return false;
    }
    return true;
}

module.exports = getStatic//注意啊原生nodejs支持支 module.exports 不支持export default等ES6写法